package com.example.user

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.RegexUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.lib_base.mvvm.BaseActivity
import com.example.user.databinding.ActivityUpdatePwdBinding
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@Route(path = "/user/UpdatePwdActivity")
class UpdatePwdActivity : BaseActivity<ActivityUpdatePwdBinding,UserViewModel>() {
    override fun initView() {
        val phone = SPUtils.getInstance().getString("phone")
        binding.tvPhone.text = "当前手机号:"+phone.replaceRange(3,7,"****")
        /**
         * 默认修改密码不可用，当输入验证码（6位）时，密码可用
         */
        binding.btnUpdate.isEnabled = false
        //点击发送验证码  通知 倒计时
        binding.btnSendcode.setOnClickListener {
            viewModel.sendCode(phone)
        }
        //监听验证码
        binding.etCode.addTextChangedListener(object :TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if(binding.etCode.text.toString().length==6){
                    binding.btnUpdate.isEnabled = true
                }else{
                    binding.btnUpdate.isEnabled = false
                }
            }

            override fun afterTextChanged(s: Editable?) {
            }
        })
        binding.btnUpdate.setOnClickListener {
            val etpwd = binding.etPwd.text.toString()
            val etRepwd = binding.etRepwd.text.toString()
            if(etpwd.isEmpty()||etRepwd.isEmpty()){
                ToastUtils.showLong("密码不能为空")
                return@setOnClickListener
            }
            if(!RegexUtils.isMatch("^[\\w]{8,20}(?<!_)$",etpwd)){
                ToastUtils.showLong("密码格式不正确，应该为字母数字下划线组合")
                return@setOnClickListener
            }
            if(etpwd!=etRepwd){
                ToastUtils.showLong("两次密码不一致")
                return@setOnClickListener
            }
            viewModel.updatePwd(phone,binding.etCode.text.toString(),etpwd)
        }
    }

    override fun initData() {
        viewModel.sendCodeSuccess.observe(this){
            if(it.code==200){
                //发送通知
                val manager =
                    getSystemService(NOTIFICATION_SERVICE) as NotificationManager
                if(Build.VERSION.SDK_INT>Build.VERSION_CODES.O){
                    //高版本
                    val notificationChannel = NotificationChannel(
                        "channelId",
                        "channelName",
                        NotificationManager.IMPORTANCE_DEFAULT
                    )
                    manager.createNotificationChannel(notificationChannel)
                    val intent = Intent(this,UpdatePwdActivity::class.java)
                    val pendingIntent = PendingIntent.getActivity(
                        this,
                        102,
                        intent,
                        PendingIntent.FLAG_UPDATE_CURRENT
                    )
                    val notification = Notification.Builder(this)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentTitle("提示")
                        .setContentText("验证码:${it.data.content.substring(8, 14)}")
                        .setAutoCancel(true)//点击自动消失
                        .setContentIntent(pendingIntent)//当app退出时，点击通知后，可拉起app，展示指定activity
                        .setChannelId("channelId")
                        .build()
                    manager.notify(1,notification)
                }else{
                    val notification = Notification.Builder(this)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentTitle("提示")
                        .setContentText("验证码:${it.data.content.substring(8, 14)}")
                        .build()
                    manager.notify(1,notification)
                }
                //开启倒计时
                lifecycleScope.launch {
                    binding.btnSendcode.isEnabled = false
                    for (i in 10 downTo 1){
                        delay(1000)
                        binding.btnSendcode.text = "${i}秒后再次获取"
                    }
                    binding.btnSendcode.text = "获取验证码"
                    binding.btnSendcode.isEnabled = true
                }
            }
        }
        viewModel.updatePwdSuccess.observe(this){
            ToastUtils.showLong(it.message)
            if(it.code==200){
                finish()
            }
        }
    }

    override fun getViewModel(): Class<UserViewModel>  = UserViewModel::class.java

    override fun getLayout(): Int  = R.layout.activity_update_pwd

}